//去除字符串两端空格的原型方法
if (!("Trim" in String.prototype)) {
	String.prototype.Trim = function() {
		return this.replace(/(^\s*)|(\s*$)/g, "");
	}
}

var dom = {}; // 存储表单对象，节省dom查找的开销

var focus = {
	idimgfronturl : '', // 图片正面
	idimgbackurl : '', // 图片反面
	imgRule : /\.png$|\.bmp$|\.jpg$|\.jpeg$|\.gif$/i,
	userRule : /^([a-zA-Z]{1}\w{5,17})?$/,
	phoneRule : /^1[3|4|5|7|8][0-9]\d{4,8}$/,
	idnumberRule : /^([1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2})$/,
	pwdRule : /^[a-zA-Z]\w{5,17}$/,
	nameRule : /^[\·\u4E00-\u9FFF\u3400-\u4DFF]{2,}$/, // /^([\u4E00-\u9FA5]{2,5})$/,
	formData1:new FormData(),
	formData2:new FormData(),
	formData : {
		userCode : '', // 用户登录名
		password : '', // 用户密码
		userName : '', // 用户真实姓名
		idNumber : '', // 证件号码
		cardImg : '', // 身份证图片地址 (正面照片,反面照片) 以逗号分隔
		userTel : '', // 联系方式手机号
	},
	state : {
		user : false,
		idcard : false,
		phone : false
	},
	stateMsg : {
		userMsg : '登陆账户已经存在',
		userMsg1 : '请输入字母开头的6-18位数字、字母或下划线！',
		userMsg2 : '请输入字母开头的6-18位数字、字母或下划线！',

		idcardMsg : '身份证已经存在',
		idcardMsg1 : '身份证不能为空',
		idcardMsg2 : '身份证格式错误',

		phoneMsg : '手机号已经存在',
		phoneMsg1 : '手机号不能为空',
		phoneMsg2 : '手机号格式错误',

		nameMsg : '请输入不少于2位的汉字 可包含"·"',
		pwdMsg:'请输入字母开头的6-18位数字、字母或下划线！'
	}
}

// 图片格式
function checkImgType(file) {
	if (file) {
		if (!focus.imgRule.test(file.name)) {
			return false;
		} else {
			return true;
		}
	}
	return false
}

// 图片大小5M以内
function checkPicSizes(file) {
	if (file.size > 5242880) {
		return false;
	}
	return true;
}

function uploadFile(event, cls, statCls) {
	event = event || window.event;

	// console.info("--->>11",$('.idcardPositiveImg')[0].files[0]);
	// var file;
	// var fileSize ;
	// console.info(event.target.value);
	// console.info(event);
	if (window.FormData) {

		// if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
		//    	
		// //file = event.target.value;
		// }

		// else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
		// file = event.target.files.item(0);
		// } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
		// file = event.target.files.item(0);
		// }

		// console.info(url)

		if (!event.target.files[0]) {
			var filePath = event.target.value;

			var image = new Image();
			image.src = filePath;

			if (image.readyState == "complete") {// 已经load完毕，直接打印文件大小
				fileSize = image.fileSize;
			} else {
				image.onreadystatechange = function() {
//					alert(image.readyState);
					if (image.readyState == 'complete') {// 当图片load完毕
						fileSize = image.fileSize;
					}
				}
			}

			// var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
			// var file = fileSystem.GetFile (filePath);
			// fileSize = file.Size;
			// var name = event.target.value;
			// var fileName =
			// filePath.substring(filePath.lastIndexOf(".")+1).toLowerCase()

			console.info(fileSize);

		} else {
			// fileSize = target.files[0].size;
		}
		console.info($('#img1Input').find('.idcardPositiveImg'));
		var file = event.target.files[0];
		console.info(file)
		if (!checkImgType(file)) {
			alert("上传照片格式不支持");
			return false;
		}
		if (!checkPicSizes(file)) {
			alert("上传照片体积过大(5M以内)");
			return false;
		}
		var img = $('.registerBox').find(cls)[0];
		if (typeof (window.File) && typeof (window.FileList)
				&& typeof (window.FileReader) && typeof (window.Blob)) {
			var reader = new FileReader();
			reader.onload = function(e) {
				img.src = e.target.result.replace('data:', 'data:image/gif;');
				if (statCls == 1) {
//					var formData = new FormData();
					focus.formData1.append('file',$('.idcardPositiveImg')[0].files[0]);
//					POSTFormData(formData, 1)
				}
				if (statCls == 2) {
					focus.formData2.append('file',$('.dcardOppositeImg')[0].files[0]);
//					var formData2 = new FormData();
//					formData2.append('file', $('.dcardOppositeImg')[0].files[0]);
//					POSTFormData(formData2, 2)
				}
			}
			reader.readAsDataURL(file);
		} else {
			alert("您的浏览器暂不支持传图");
		}

	} else {
		return alert("请升级您的浏览器到最高版本");
	}
}

function getFile1(event) {
	uploadFile(event, ".img1", 1)
}

function getFile2(event) {
	uploadFile(event, ".img2", 2)
}

function updateRule(cla, msg) {
	$(cla).html(msg);
	$(cla)[0].style.color = '#ff0101';
}

$(document)
		.ready(
				function(e) {
					$("#idcardPositiveImg").on('change', getFile1);
					$("#dcardOppositeImg").on('change', getFile2);

					$("#userInput").blur(function(event) {
						val = $("#userInput").val().Trim();
						if (val == '') {
							updateRule(".userRule", focus.stateMsg.userMsg1);
							return false;
						}
						if (!focus.userRule.test(val)) {
							updateRule(".userRule", focus.stateMsg.userMsg2);
							return false;
						}
						isUserIsPro(val);
					});

					$("#idcardInput").blur(
							function(event) {
								var val = $("#idcardInput").val().Trim();
								if (val == '') {
									updateRule(".idcardRule",
											focus.stateMsg.idcardMsg1);
									return false;
								}
								if (!focus.idnumberRule.test(val)) {
									updateRule(".idcardRule",
											focus.stateMsg.idcardMsg2);
									return false;
								}
								isIdNumber(val);
							});
					$("#phoneInput").blur(function(event) {
						var val = $("#phoneInput").val().Trim();
						if (val == '') {
							updateRule(".phoneRule", focus.stateMsg.phoneMsg1);
							return false;
						}
						if (!focus.phoneRule.test(val)) {
							updateRule(".phoneRule", focus.stateMsg.phoneMsg2);
							return false;
						}
						isUserTel(val);
					});

					$("#pwdInput").blur(function(event) {
						var val = $("#pwdInput").val().Trim();
						if (val == '') {
							updateRule(".pwdRule", "密码不能为空");
							return false;
						}
						if (!focus.pwdRule.test(val)) {
							updateRule(".pwdRule", focus.stateMsg.pwdMsg);
							return false;
						}
						updateRule(".pwdRule", '');
					});

					$("#confirmPwdInput").blur(function(event) {
						var pwd = $("#pwdInput").val().Trim();
						var val = $("#confirmPwdInput").val().Trim();
						if (val != pwd) {
							updateRule(".confirmpwdRule", "两次密码不一致");
							return false;
						}
						updateRule(".confirmpwdRule", '');
					});

					$("#nameInput").blur(function(event) {
						var val = $("#nameInput").val().Trim();
						if (val == '') {
							updateRule(".nameRule", "真实姓名不能为空！");
							return false;
						}
						if (!focus.nameRule.test(val)) {
							updateRule(".nameRule", focus.stateMsg.nameMsg);
							return false;
						}
						updateRule(".nameRule", '');
					});

					// $('#userInput').focus();
					// var $inp = $('#userInput');
					// $inp.bind('keydown', function (e) {

					// var key = e.which;
					// if (key == 13) {
					// $('#errorMessage').hide();
					// if($('#detail_isbn').val()==''){
					// ajaxAlertErrorMsg("请录入isbn码!", true);
					// return false;
					// }
					// BMEP.Invoice.PreCheckIn.main();
					// }
					// });

					// 获得3个输入框并为其绑定回车事件
					var tempArray = $("input[type='text'],input[type='password'],input[type='file'],input[type='checkbox']");
					for (var i = 0; i < tempArray.length; i++) {
						dom[tempArray[i].id] = $(tempArray[i]);
						(function(obj, index) {
							obj.keyup(function(e) {
								var nowKey = e.keyCode;
								if (nowKey == 13) {
									if (index >= tempArray.length - 1) {
										login();
									} else {
										$(tempArray[index + 1]).focus();
									}
								} else {
									$(this).removeClass("error");
								}
							});
						})($(tempArray[i]), i);
					}
					// 登录按钮事件绑定

					dom.registerBtn = $("#registerBtn");
					dom.returnBtn = $(".return");
					
					dom.returnBtn.click(function() {
						window.location.href = './register.html';
					});
					
					dom.registerBtn.click(function() {
						register();
					});
					dom.messageTips = $("#messageTips");
				});

function registerTest() {
	var obj = {
		user : 'nick12345',
		password : '12121212',
		confirmpwd : '12121212',
		idcard : '412622187837674876',
		phone : '17011976738',
		name : '波波',
	}
	dom.userInput.val(obj.user);
	dom.pwdInput.val(obj.password);
	dom.confirmPwdInput.val(obj.confirmpwd);
	dom.nameInput.val(obj.name);
	dom.idcardInput.val(obj.idcard);
	dom.phoneInput.val(obj.phone);
}

// 验证注册
function register() {
	var user = dom.userInput.val().Trim();
	dom.userInput.val(user);

	var password = dom.pwdInput.val().Trim();
	dom.pwdInput.val(password);

	var name = dom.nameInput.val().Trim();
	dom.nameInput.val(name);

	var idcard = dom.idcardInput.val().Trim();
	dom.idcardInput.val(idcard);

	var phone = dom.phoneInput.val().Trim();
	dom.phoneInput.val(phone);

	var confirmpwd = dom.confirmPwdInput.val().Trim();
	dom.confirmPwdInput.val(confirmpwd);

	if (user == '') {
		showMessage(".userRule", focus.stateMsg.userMsg1);
		return false;
	}

	if (!focus.userRule.test(user)) {
		showMessage(".pwdRule", focus.stateMsg.userMsg2);
		return false;
	}

	if (password == '') {
		showMessage(".pwdRule", "密码不能为空");
		return false;
	}

	if (!focus.pwdRule.test(password)) {
		showMessage(".pwdRule", focus.stateMsg.pwdMsg);
		return false;
	}

	if (password != confirmpwd) {
		showMessage(".confirmpwdRule", "两次密码不一致");
		return false;
	}

	if (name == '') {
		showMessage(".nameRule", "真实姓名不能为空！");
		return false;
	}
	if (!focus.nameRule.test(name)) {
		updateRule(".nameRule", focus.stateMsg.nameMsg);
		return false;
	}
	if (idcard == '') {
		showMessage(".idcardRule", focus.stateMsg.idcardMsg1);
		return false;
	}

	if (focus.idnumberRule.test(idcard) === false) {
		return false;
	}

	if (phone == '') {
		updateRule(".phoneRule", focus.stateMsg.phoneMsg1);
		return false;
	}

	if (!focus.phoneRule.test(phone)) {
		showMessage(".idcardPositiveRule", '手机号格式错误！');
		return false;
	}
	if ($(".idcardPositiveImg").val() == "") {
		showMessage(".idcardPositiveRule", '请选择身份证正面！');
		return false;
	}
	
	
	
	
	
	if ($(".dcardOppositeImg").val() == "") {
		showMessage(".dcardOppsiteRule", '请选择身份证反面！');
		return false;
	}

	if (!document.getElementById("agreementInput").checked) {
		showMessage("warning", '请先阅读并同意《安居365注册协议》！', dom.phoneInput);
		return false;
	}

	if (!focus.state.user) {
		showMessage("warning", focus.stateMsg.userMsg);
		return false;
	}
	if (!focus.state.idcard) {
		showMessage("warning", focus.stateMsg.idcardMsg);
		return false;
	}
	if (!focus.state.phone) {
		showMessage("warning", focus.stateMsg.phoneMsg);
		return false;
	}

	
	
//	POSTFormData(focus.formData2, 2)
	
	focus.formData.userCode = user;
	focus.formData.password = password;
	focus.formData.userName = name;
	
	focus.formData.userTel = phone;
	focus.formData.idNumber = idcard;
	POSTFormData(focus.formData1, 1)
//	console.info(focus.formData);
}

// 账户名 排重
function isUserIsPro(user) {
	$.ajax({
		url : '../../regist/userIsPro.svc',
		type : "POST",
		data : JSON.stringify({
			userCode : user
		}),
		async : true,
		success : function(data) {
			if (data.succ) {
				if (data.result == "1")
					updateRule(".userRule", focus.stateMsg.userMsg);
				else {
					$(".userRule").html(''), focus.state.user = data.succ;
				}
				;
			}
		},
		error : function(data) {
			showMessage("error", "提交失败，请稍后再试");
		}
	})
}

// 身份证 排重
function isIdNumber(idcard) {
	$.ajax({
		url : '../../regist/idNumberIsPro.svc',
		type : "POST",
		data : JSON.stringify({
			idNumber : idcard
		}),
		async : true,
		success : function(data) {
			if (data.result == "1")
				updateRule(".idcardRule", focus.stateMsg.idcardMsg);
			else {
				$(".idcardRule").html('');
				focus.state.idcard = data.succ;
			}
		},
		error : function(data) {
			showMessage("error", "提交失败，请稍后再试");
		}
	})
}

// 联系⼿机号排重
function isUserTel(phone) {

	$.ajax({
		url : '../../regist/userTelIsPro.svc',
		type : "POST",
		data : JSON.stringify({
			userTel : phone
		}),
		async : true,
		success : function(data) {
			if (data.result == "1")
				updateRule(".phoneRule", focus.stateMsg.phoneMsg);
			else {
				$(".phoneRule").html('');
				focus.state.phone = data.succ;
			}
		},
		error : function(data) {
			showMessage("error", "提交失败，请稍后再试");
		}
	})
}
function addUser(){
	$.ajax({
		url : '../../regist/addUserComEntity.svc',
		type : "POST",
		data : JSON.stringify({
			userComEntity : focus.formData
		}),
		async : true,
		success : function(data) {
			if (data.succ) {
				showMessage("success", "提交成功，等待管理员审核！");
				setTimeout(function() {
					window.location.href = '../../anju365.html';
				}, 800);
			}
		},
		error : function(data) {
			showMessage("error", "提交失败，请稍后再试！");
		}
	})
}

// 反馈提示信息
function showMessage(typeStr, msg, obj) {

	alert(msg);

	// dom.messageTips.text(msg);
	// dom.messageTips[0].className = "";
	// dom.messageTips.addClass(typeStr);
	// if (obj) {
	// obj.focus();
	// if (typeStr != "ok" && typeStr != "normal") {
	// obj.addClass("error");
	// }
	// } else {
	// dom.userInput.removeClass("error");
	// dom.pwdInput.removeClass("error");
	// // dom.verifyInput.removeClass("error");
	// }
}

function POSTFormData(formdata, sequence) {
	console.info(formdata)
	var xhr;
	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
	} else {
		xhr = new ActiveXObject;
	}
	xhr.onload = function(oEvent) {
		if (xhr.readyState == 4 && xhr.status == 200) {
			var obj = eval('(' + xhr.responseText + ')');
			if (sequence == '1') {
				focus.idimgfronturl = obj.result;
			}
			if (sequence == '2') {
				focus.idimgbackurl = obj.result;
			}
			console.info(focus.idimgfronturl)
		} else {
		}
	};
	var http =  "../../regist/photoSave.svc";
	xhr.open("POST", http, true);
	xhr.send(formdata);
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4 && xhr.status == 200) {
			var obj = eval('(' + xhr.responseText + ')');
			console.info(xhr.responseText);
			if (sequence == '1') {
				focus.idimgfronturl = obj.result;
				POSTFormData(focus.formData2, 2)
			}
			if (sequence == '2') {
				focus.idimgbackurl = obj.result;
				focus.formData.cardImg = focus.idimgfronturl + ',' + focus.idimgbackurl;
				addUser();
			}
		} else {
		}
	}
}
